package cn.muqingfeng.bbs.ui;

import java.io.File;
import java.util.HashMap;
import java.util.regex.Matcher;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.util.EntityUtils;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.net.Uri;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import cn.muqingfeng.api.RequestHelper;
import cn.muqingfeng.api.UriHelper;
import cn.muqingfeng.api.request.GsonRequest;
import cn.muqingfeng.api.to.BaseResponseTO;
import cn.muqingfeng.api.to.RegistTO;
import cn.muqingfeng.api.to.UserTO;
import cn.muqingfeng.bbs.R;
import cn.muqingfeng.bbs.constants.Constants;
import cn.muqingfeng.bbs.ui.widget.AvatarPickerPopup;
import cn.muqingfeng.util.AccountManager;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.google.gson.Gson;

public class RegistActivity extends BaseActivity implements OnClickListener {
	private static final Object LOCK = new Object();
	private EditText mUserNameView;
	private EditText mEmailView;
	private EditText mPasswordView;
	private EditText mRepasswordView;
	private Button mSubmitBtn;
	private ImageView mAddAvatarView;
	private AvatarPickerPopup avatarPickerPopup;
	private String mAvatarPath;
	private boolean isRegist = false;
	private ProgressDialog mDialog;
	private HttpPost mUploadRequest;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.regist);
		setupViews();
	}

	private void setupViews() {
		findViewById(R.id.back).setOnClickListener(this);
		mUserNameView = (EditText) findViewById(R.id.username);
		mEmailView = (EditText) findViewById(R.id.email);
		mPasswordView = (EditText) findViewById(R.id.password);
		mRepasswordView = (EditText) findViewById(R.id.repassword);
		mSubmitBtn = (Button) findViewById(R.id.submit);
		mSubmitBtn.setOnClickListener(this);
		mAddAvatarView = (ImageView) findViewById(R.id.avatar);
		mAddAvatarView.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back:
			finish();
			break;
		case R.id.avatar:
			avatarPickerPopup = new AvatarPickerPopup(this);
			ViewGroup decor = (ViewGroup) getWindow().getDecorView();
			avatarPickerPopup.showAtLocation(decor, Gravity.BOTTOM, 0, 0);
			break;
		case R.id.submit:
			regist();
			break;
		default:
			break;
		}
	}

	private void regist() {
		synchronized (LOCK) {
			if (isRegist)
				return;
			final String username = mUserNameView.getText().toString();
			if (TextUtils.isEmpty(username) || username.length() < 3) {
				Toast.makeText(getApplicationContext(), "用户名由3-15个字符组成", Toast.LENGTH_SHORT).show();
				return;
			}
			final String password = mPasswordView.getText().toString();
			if (TextUtils.isEmpty(password) || password.length() < 6) {
				Toast.makeText(getApplicationContext(), "请填写密码, 最小长度为 6 个字符", Toast.LENGTH_SHORT).show();
				return;
			}
			final String repassword = mRepasswordView.getText().toString();
			if (!password.equals(repassword)) {
				Toast.makeText(getApplicationContext(), "两次输入密码不一致", Toast.LENGTH_SHORT).show();
				return;
			}
			final String email = mEmailView.getText().toString();
			if (TextUtils.isEmpty(email)) {
				Toast.makeText(getApplicationContext(), "请输入邮箱!", Toast.LENGTH_SHORT).show();
				return;
			}
			Matcher matcher = Constants.EMAIL_ADDRESS.matcher(email);
			if (!matcher.matches()) {
				Toast.makeText(getApplicationContext(), "请输入合法的邮箱!", Toast.LENGTH_SHORT).show();
				return;
			}
			isRegist = true;
			String requestUrl = UriHelper.getRegistUrl();
			HashMap<String, String> params = new HashMap<String, String>();
			params.put(UriHelper.PARAMS_EMAIL, email);
			params.put(UriHelper.PARAMS_PASSWORD, password);
			params.put(UriHelper.PARAMS_PASSWORD2, repassword);
			params.put(UriHelper.PARAMS_USERNAME, username);
			showDialog();
			GsonRequest<RegistTO> request = new GsonRequest<RegistTO>(Method.POST, requestUrl, new Listener<RegistTO>() {

				@Override
				public void onResponse(RegistTO response) {
					if (!isDestroied()) {
						if (response == null) {
							Toast.makeText(getApplicationContext(), "注册失败，请稍后重试！", Toast.LENGTH_SHORT).show();
							dismissDialog();
						} else {
							if (response.isSuccess()) {
								if(TextUtils.isEmpty(mAvatarPath)){
									dismissDialog();
									onRegistSuccess(response, username, repassword);
								}else{
									changeAvatar(response, username, repassword);
								}
							} else {
								dismissDialog();
								String toastMessage = response.getMessage();
								toastMessage = TextUtils.isEmpty(toastMessage) ? "注册失败，请稍后重试！" : toastMessage;
								Toast.makeText(getApplicationContext(), toastMessage, Toast.LENGTH_SHORT).show();
							}
						}
					}
				}
			}, new ErrorListener() {

				@Override
				public void onErrorResponse(VolleyError error) {
					if (!isDestroied()) {
						dismissDialog();
						Toast.makeText(getApplicationContext(), "注册失败，请稍后重试！", Toast.LENGTH_SHORT).show();
					}
				}
			}, params, RegistTO.class);
			RequestHelper.startRequest(getApplicationContext(), request);
		}
	}

	private void onRegistSuccess(RegistTO response, String username, String password) {
		Toast.makeText(getApplicationContext(), "注册成功", Toast.LENGTH_SHORT).show();
		UserTO userTO = response.getUser();
		userTO.setUsername(username);
		AccountManager.setPassword(getApplicationContext(), password);
		AccountManager.saveUser(getApplicationContext(), userTO);
		setResult(RESULT_OK);
		finish();
	}

	private void changeAvatar(final RegistTO registTO,final String username, final String password) {
		new AsyncTask<Void, Void, BaseResponseTO>() {

			@Override
			protected BaseResponseTO doInBackground(Void... params) {
				try {
					String requestUrl = UriHelper.getChangeAvatarUrl();
					AndroidHttpClient httpclient = AndroidHttpClient.newInstance(RequestHelper.UA, getApplicationContext());
					try {
						mUploadRequest = new HttpPost(requestUrl);

						FileBody bin = new FileBody(new File(mAvatarPath));

						MultipartEntity reqEntity = new MultipartEntity();
						reqEntity.addPart("Filedata", bin);
						mUploadRequest.addHeader(UriHelper.PARAMS_HEADER_USERNAME, username);
						mUploadRequest.addHeader(UriHelper.PARAMS_HEADER_PASSWORD, password);
						mUploadRequest.setEntity(reqEntity);

						HttpResponse response = httpclient.execute(mUploadRequest);
						HttpEntity resEntity = response.getEntity();
						String result = EntityUtils.toString(resEntity);
						if (!TextUtils.isEmpty(result)) {
							Gson gson = new Gson();
							return gson.fromJson(result, BaseResponseTO.class);
						}
					} finally {
						httpclient.close();
						mUploadRequest = null;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}

			protected void onPostExecute(BaseResponseTO result) {
				if (!isDestroied()) {
					dismissDialog();
					onRegistSuccess(registTO, username, password);
				}
			}
		}.execute();
	}

	private void showDialog() {
		if (mDialog != null && mDialog.isShowing()) {
			return;
		}
		mDialog = new ProgressDialog(this);
		mDialog.setCancelable(false);
		mDialog.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				isRegist = false;
				if (mUploadRequest != null) {
					mUploadRequest.abort();
				}
			}
		});
		mDialog.setMessage("正在请求，请稍等...");
		mDialog.show();
	}

	private void dismissDialog() {
		if (mDialog != null && mDialog.isShowing()) {
			mDialog.dismiss();
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}
		// 根据上面发送过去的请求码来区别
		switch (requestCode) {
		case Constants.REQUEST_CODE_PICK_PHOTO:
		case Constants.REQUEST_CODE_TAKE_PHOTO:
			mAvatarPath = data.getStringExtra("CropperPhotoPath");
			mAddAvatarView.setImageResource(R.drawable.ic_add_avatar);
			mAddAvatarView.setImageURI(Uri.fromFile(new File(mAvatarPath)));
			break;
		default:
			break;
		}
	}
}
